export function formatGetUri(obj) {
    const params = []
    Object.keys(obj).forEach((key) => {
        let value = obj[key]
        if (typeof value === 'undefined' || value === null || value === '') { } else {
            params.push([key, encodeURIComponent(value)].join('='))
        }
    })
    return '?' + params.join('&')
}
export function navto(link, query) {
    console.log('跳转')
    wx.navigateTo({
        url: link + `${formatGetUri(query)}`
    })
}
export function formatTime(time, type) {
    const date = new Date(time)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    const t1 = [formatTwo(year), formatTwo(month), formatTwo(day)].join('-')
    const t3 = month + '月' + day + '日'
    const t2 = [formatTwo(hour), formatTwo(minute), formatTwo(second)].map(formatNumber).join(':')
    if (type === 'hours') return `${t1} ${t2}`
    else if (type === 'showHours') return `${t2}`
    else if (type === 'words') {
        if (new Date(time).toDateString() === new Date().toDateString()) {
            return `今天 ${t2}`
        } else {
            return `${t3} ${t2}`
        }
    } else return `${t1}`
}
const formatTwo = n => {
    if (n >= 10) return '' + n
    else return '0' + n
}
const formatNumber = n => {
    const str = n.toString()
    return str[1] ? str : `0${str}`
}
export function timeCha(time) {
    var d2 = time
    var d1 = new Date().getTime()
    var d3 = new Date(d2 - d1)
    let timeChaData = formatTwo((d3).getHours()) + ':' + formatTwo((d3).getMinutes()) + ':' + formatTwo((d3).getSeconds())
    return timeChaData
}
export function timeFn(d1, type) {
    var dateBegin = d1
    var dateEnd = new Date()
    var dateDiff = Math.abs(dateBegin - dateEnd.getTime())
    var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000))
    var leave1 = dateDiff % (24 * 3600 * 1000)
    var hours = Math.floor(leave1 / (3600 * 1000))
    var hours2 = Math.floor(leave1 / (3600 * 1000)) + dayDiff * 24
    var leave2 = leave1 % (3600 * 1000)
    var minutes = Math.floor(leave2 / (60 * 1000))
    var leave3 = leave2 % (60 * 1000)
    var seconds = Math.round(leave3 / 1000)
    if (type === 'words') return formatTwo(hours) + ':' + formatTwo(minutes) + ':' + formatTwo(seconds)
    else if (type === 'hours') return formatTwo(hours2) + ':' + formatTwo(minutes) + ':' + formatTwo(seconds)
    else return dayDiff + '天' + formatTwo(hours) + ':' + formatTwo(minutes) + ':' + formatTwo(seconds)
}
//   export async function verifyGoodsStockFun (formData, callBack) {
//     const data = await verifyGoodsStock(formData)
//     callBack(data)
//   }
// 跳转tabBar
export function navHome(link) {
    wx.switchTab({
        url: link
    })
}
// 跳转tabBar
export function redirectTo(link) {
    wx.redirectTo({
        url: link
    })
}
// 多张图片放大预览
export function previewImgUrl(currentImg, urls) {
    var url = []
    for (var i = 0; i < urls.length; i++) {
        url.push(urls[i])
    }
    previewImg(currentImg, url)
}
// 图片放大
export function previewImg(current, urls) {
    wx.previewImage({
        current: current,
        urls: urls
    })
}
// 微信支付
export function requestPayment(res, callback, failBack) {
    console.log(res)
    wx.requestPayment({
        'timeStamp': res.timeStamp,
        'nonceStr': res.nonceStr,
        'package': res.pkg,
        'signType': 'MD5',
        'paySign': res.paySign,
        'success': function (res) {
            callback(res)
        },
        'fail': function (res) {
            failBack()
        }
    })
}
// 跳转t
export function redirectToQuery(link, query) {
    wx.redirectTo({
        url: link + `${formatGetUri(query)}`
    })
}
// 是否为手机号
export function isPhone(str) {
    const reg = /^[1][3,4,5,7,8][0-9]{9}$/
    return reg.test(str)
}
// 是否为邮箱
export function isEmail(str) {
    const reg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
    return reg.test(str)
}
/**
 * 节流函数
 */
export function throttle(func, wait, options) {
    /* options的默认值
     *  表示首次调用返回值方法时，会马上调用func；否则仅会记录当前时刻，当第二次调用的时间间隔超过wait时，才调用func。
     *  options.leading = true;
     * 表示当调用方法时，未到达wait指定的时间间隔，则启动计时器延迟调用func函数，
     * 若后续在既未达到wait指定的时间间隔和func函数又未被调用的情况下调用返回值方法，则被调用请求将被丢弃。
     *  options.trailing = true; 
     * 注意：当options.trailing = false时，效果与上面的简单实现效果相同
     */
    var context, args, result;
    var timeout = null;
    var previous = 0;
    if (!options) options = {};
    var later = function () {
        previous = options.leading === false ? 0 : new Date().getTime();
        timeout = null;
        result = func.apply(context, args);
        if (!timeout) context = args = null;
    };
    return function () {
        var now = new Date().getTime();
        console.log(now)
        if (!previous && options.leading === false) previous = now;
        // 计算剩余时间
        var remaining = wait - (now - previous);
        context = this;
        args = arguments;
        // 当到达wait指定的时间间隔，则调用func函数
        // 精彩之处：按理来说remaining <= 0已经足够证明已经到达wait的时间间隔，但这里还考虑到假如客户端修改了系统时间则马上执行func函数。
        if (remaining <= 0 || remaining > wait) {
            // 由于setTimeout存在最小时间精度问题，因此会存在到达wait的时间间隔，但之前设置的setTimeout操作还没被执行，因此为保险起见，这里先清理setTimeout操作
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            previous = now;
            result = func.apply(context, args);
            if (!timeout) context = args = null;
        }
        else if (!timeout && options.trailing !== false) {
            // options.trailing=true时，延时执行func函数
            timeout = setTimeout(later, remaining);
        }
        return result;
    };
};